package com.lipi.mall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lipi.common.to.mq.SeckillOrderTO;
import com.lipi.common.utils.R;
import com.lipi.common.vo.MemberRespVO;
import com.lipi.mall.seckill.feign.CouponFeiService;
import com.lipi.mall.seckill.feign.ProductFeignService;
import com.lipi.mall.seckill.interceptor.LoginUserInterceptor;
import com.lipi.mall.seckill.service.SeckillService;
import com.lipi.mall.seckill.to.SecKillSkuRedisTO;
import com.lipi.mall.seckill.vo.SeckillSesssionsWithSkus;
import com.lipi.mall.seckill.vo.SkuInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeiService couponFeiService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //扫描最近三天需要上架的商品
        R r = couponFeiService.getLasted3DaySession();
        if (r.getCode() == 0) {
            List<SeckillSesssionsWithSkus> data = r.getData(new TypeReference<List<SeckillSesssionsWithSkus>>() {
            });
            //将数据缓存到redis
            //1、缓存活动信息
            saveSessionInfos(data);
            //2、缓存活动商品信息
            saveSessionSkuInfos(data);

        }
    }

    /**
     * 返回当前时间可以参与的秒杀活动商品信息
     *
     * @return
     */
    @Override
    public List<SecKillSkuRedisTO> getCurrentSeckillSkus() {

        try (Entry entry = SphU.entry("seckillSkus")) {

            // 1、redis中查询当前场次的秒杀活动商品
            // 确定当前的秒杀场次
            long time = new Date().getTime();
            // 查询出所有的key
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");

            for (String key : keys) {

                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                //活动场次的开始和结束时间
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);

                if (time >= start && time <= end) {
                    //2、获取这个场次的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, 0, -1);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);

                    if (!CollectionUtils.isEmpty(list)) {
                        List<SecKillSkuRedisTO> collect = list.stream()
                                .map(item -> {
                                    SecKillSkuRedisTO redisTO = JSON.parseObject(item.toString(), new TypeReference<SecKillSkuRedisTO>() {
                                    });
                                    //屏蔽随机码
                                    //redisTO.setRandomCode(null);
                                    return redisTO;
                                })
                                .collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("流量过大...");
        }


        return null;
    }

    @Override
    public SecKillSkuRedisTO getSkuSeckillInfo(Long skuId) {
        //1、找到所有参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (!CollectionUtils.isEmpty(keys)) {
            String regx = "\\d_" + skuId.toString();
            for (String key : keys) {
                //正则匹配,看右边是否拥有skuId
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SecKillSkuRedisTO secKillSkuRedisTO = JSON.parseObject(json, SecKillSkuRedisTO.class);

                    //若当前不是秒杀时间,屏蔽随机码
                    Long startTime = secKillSkuRedisTO.getStartTime();
                    Long end = secKillSkuRedisTO.getEndTime();
                    Long currentTime = new Date().getTime();

                    if (!(currentTime >= startTime && currentTime <= end)) {
                        secKillSkuRedisTO.setRandomCode(null);
                    }
                    return secKillSkuRedisTO;
                }
            }
        }

        return null;
    }

    /**
     * 秒杀订购商品
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, String num) {
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();

        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }

        SecKillSkuRedisTO skuRedisTO = JSON.parseObject(json, new TypeReference<SecKillSkuRedisTO>() {
        });

        // 1、合法性校验
        // 1.1、秒杀时间确认
        Long startTime = skuRedisTO.getStartTime();
        Long endTime = skuRedisTO.getEndTime();
        Long currentTime = new Date().getTime();

        if (!(currentTime >= startTime && currentTime <= endTime)) {
            //时间不合法
            return null;
        }

        // 1.2、随机码校验
        String randomCode = skuRedisTO.getRandomCode();
        if (!randomCode.equalsIgnoreCase(key)) {
            //随机码不一致
            return null;
        }

        // 1.3、购买数量校验
        if (skuRedisTO.getSeckillLimit() < Integer.valueOf(num)) {
            //购买件数过多
            return null;
        }

        // 1.3.2 校验用户有没有已经参与过该场次该商品的秒杀
        Long memberId = memberRespVO.getId();
        //约束:每当用户购买秒杀商品,redis将会存储该用户的购买记录,key=#{memberId}_#{sessionId}_#{skuId}
        String abSentKey = memberId + "_" + skuRedisTO.getPromotionSessionId() + "_" + skuRedisTO.getSkuId();
        //自动过期
        Long ttl = endTime - currentTime;
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(abSentKey, num, ttl, TimeUnit.MILLISECONDS);

        if (!aBoolean) {
            //absent失败,用户已购买过
            return null;
        }

        // 2、秒杀逻辑
        // 2.1、获取信号量
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

        boolean b = semaphore.tryAcquire(Integer.parseInt(num));

        if (b) {
            //秒杀成功,快速下单并将具体订单业务交给MQ
            String orderSn = IdWorker.getTimeId();
            SeckillOrderTO orderTO = new SeckillOrderTO();
            orderTO.setOrderSn(orderSn);
            orderTO.setMemberId(memberId);
            orderTO.setNum(Integer.valueOf(num));
            orderTO.setPromotionSessionId(skuRedisTO.getPromotionSessionId());
            orderTO.setSeckillPrice(skuRedisTO.getSeckillPrice());
            orderTO.setSkuId(skuRedisTO.getSkuId());

            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTO);

            return orderSn;
        }


        return null;

    }


    private void saveSessionInfos(List<SeckillSesssionsWithSkus> sesssions) {
//        //循环处理场次信息
//        sesssions.stream().forEach(sesssion -> {
//
//            Long startTime = sesssion.getStartTime().getTime();
//            Long endTime = sesssion.getEndTime().getTime();
//
//            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
//
//            //防重,有这个key了就不再操作了
//            if (!redisTemplate.hasKey(key)) {
//                //value: sessionId_skuId
//                List<String> collect = sesssion.getRelationSkus().stream()
//                        .map(item -> {
//                            return item.getPromotionSessionId() + "_" + item.getSkuId().toString();
//                        })
//                        .collect(Collectors.toList());
//                redisTemplate.opsForList().leftPushAll(key, collect);
//            }
//
//
//        });

        if (sesssions != null)
            sesssions.stream().forEach(sesssion -> {
                Long startTime = sesssion.getStartTime().getTime();
                Long endTime = sesssion.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = redisTemplate.hasKey(key);
                if (!hasKey) {
                    List<String> collect = sesssion.getRelationSkus().stream()
                            .map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString())
                            .collect(Collectors.toList());
                    //缓存活动信息
                    redisTemplate.opsForList().leftPushAll(key, collect);
                    //TODO 设置过期时间[已完成]
                    redisTemplate.expireAt(key, new Date(endTime));
                }
            });
    }

    private void saveSessionSkuInfos(List<SeckillSesssionsWithSkus> sesssions) {
        if (sesssions != null)
            sesssions.stream().forEach(sesssion -> {
                //准备hash操作
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                sesssion.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    //4、随机码？  seckill?skuId=1&key=dadlajldj；
                    String token = UUID.randomUUID().toString().replace("-", "");

                    if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                        //缓存商品
                        SecKillSkuRedisTO redisTo = new SecKillSkuRedisTO();
                        //1、sku的基本数据
                        R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVO info = skuInfo.get("skuInfo", new TypeReference<SkuInfoVO>() {
                            });
                            redisTo.setSkuInfo(info);
                        }

                        //2、sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        //3、设置上当前商品的秒杀时间信息
                        redisTo.setStartTime(sesssion.getStartTime().getTime());
                        redisTo.setEndTime(sesssion.getEndTime().getTime());

                        redisTo.setRandomCode(token);
                        String jsonString = JSON.toJSONString(redisTo);
                        //TODO 每个商品的过期时间不一样。所以，我们在获取当前商品秒杀信息的时候，做主动删除，代码在 getSkuSeckillInfo 方法里面
                        ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), jsonString);
                        //如果当前这个场次的商品的库存信息已经上架就不需要上架
                        //5、使用库存作为分布式的信号量  限流；
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        //商品可以秒杀的数量作为信号量
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                        //TODO 设置过期时间。
                        semaphore.expireAt(sesssion.getEndTime());
                    }
                });
            });
    }


//    private void saveSessionInfos(List<SeckillSesssionsWithSkus> seckillSesssionsWithSkus) {
//        seckillSesssionsWithSkus.stream()
//    }
//
//    private void saveSessionSkuInfos(List<SeckillSesssionsWithSkus> seckillSesssionsWithSkus) {
//
//    }


}
